import React, { useState, useRef, useEffect, useCallback } from 'react';
import { ProCard, ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, Col, Form, Modal, Row, Space, Table, Tag, message, } from 'antd';
import type { Key } from 'antd/lib/table/interface';
import ExportJsonExcel from "js-export-excel";
import { connect } from 'umi';
import type { Dispatch } from 'umi';
import JSZip from 'jszip';
import FileSaver from 'file-saver'
import axios from 'axios';
import { PageContainer } from '@ant-design/pro-layout';
export type Props = {
    dispatch?: Dispatch;
    getDetialTableListData?: any;
    notificationId?: any;
};
const statusMap = [
    {
        color: 'green',
        text: '已读',
    },
    {
        color: 'red',
        text: '未读',
    },
];
//定义通知标题样式
const titleStyle = {
    fontWeight: 'bolder',
    fontSize: '20px',
    color: 'black',
};
//定义通知内容样式
const contentStyle = {
    whiteSpace: 'pre-wrap',
    textAlign: 'left',
    fontSize: '16px',
    lineHeight: '1.5',
};
const roles = ['辅导员', '班导师', '班长', '团支书'];
const classes = ['电气2301', '电气2302', '电气2303', '电气2304'];
const notifications = [
    '学习计划会议将于明天召开，请准时参加。',
    '本周体育活动推迟至下周，请做好准备。',
    '学校开展环境保护志愿者招募，请有兴趣的同学报名。',
    '各班班长请于本周五参加班长会议。',
    '团委组织乡村义务劳动活动，报名截止本周五。',
    '辅导员将于明天下午在办公室接待同学。',
];
export type Status = {
    color: string;
    text: string;
};
export type TableListItem = {
    key: number;
    stuName: string;
    callNumber: string;
    status: Status;
    isRead: string;
    stuCode: string;
    phoneNumber: string;
    majorLabel: string;
    classLabel: string;
    fileId: string;
    receipt: string;
    isUpLoad: string;
};
//制造假数据
const tableListDataSource: TableListItem[] = [];
for (let i = 0; i < 50; i += 1) {
    tableListDataSource.push({
        key: i,
        stuName: roles[Math.floor(Math.random() * roles.length)],
        stuCode: Math.floor(Math.random() * 1000).toString(),
        callNumber: notifications[Math.floor(Math.random() * notifications.length)],
        status: statusMap[Math.floor(Math.random() * 10) % 2],
        isRead: "",
        fileId: "",
        receipt: "",
        isUpLoad: "否",
        phoneNumber: Math.floor(Math.random() * 1000000).toString(),
        majorLabel: "电气",
        classLabel: classes[Math.floor(Math.random() * roles.length)],
    });
    tableListDataSource.forEach(item => {
        item.isRead = item.status.text
    })
}
//columns=useState()
const columns: ProColumns<TableListItem>[] = [
    {
        title: '序号',
        align: 'center',
        width: 120,
        dataIndex: 'key',
    },
    {
        title: '姓名',
        width: 120,
        align: 'center',
        dataIndex: 'stuName',
    },
    {
        title: '学号',
        width: 120,
        align: 'center',
        dataIndex: 'stuCode',
    },
    {
        title: '专业',
        width: 120,
        align: 'center',
        dataIndex: 'majorLabel',
    },
    {
        title: '班级',
        width: 120,
        align: 'center',
        dataIndex: 'classLabel',
    },
    {
        title: '状态',
        width: 120,
        dataIndex: 'status',
        render: (_, record) => <Tag color={record.status?.color}>{record.status?.text}</Tag>,
        // 1. 添加filters属性用于配置筛选选项
        filters: [
            { text: '已读', value: '已读' },
            { text: '未读', value: '未读' },
        ],
        filterMultiple: false,
        // 2. 添加onFilter属性用于指定筛选处理函数
        onFilter: (value, record) => record.status?.text === value
    },
    {
        title: '联系方式',
        width: 120,
        align: 'center',
        dataIndex: 'phoneNumber',
    },
];

const DetialList: React.FC = (props: any) => {
    // 使用useState钩子创建表格数据源的状态变量tableListData
    const [filteredInfo, setFilteredInfo] = useState({ status: "" });
    // 使用useState钩子创建状态变量，用于存储用户选择的行的keys
    const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
    const tableListNewData: TableListItem[] = [];
    const [title, setTitle] = useState(false)
    const settableData = (pagination, filters, sorter) => {
        setFilteredInfo(filters);
    }
    //单个文件下载
    const getDownLoad = (value: any) => {
        console.log(value)
        window.open("/api/freshSystem/downloadFile/" + value)
    }
    //下载列表（包括筛选）
    const downloadData = (value: TableListItem[]) => {
        tableListNewData.splice(0, tableListNewData.length)
        console.log(filteredInfo.status)
        value.forEach(item => {
            console.log(item)
            if (filteredInfo.status == null || filteredInfo.status == "") tableListNewData.push(item)
            else if (filteredInfo.status.includes(item.isRead)) tableListNewData.push(item)
        })
        if (!title) handleExportCurrentExcel(tableListNewData)
        else handleExportCurrentExcel2(tableListNewData)
    }
    // 请求文件资源
    const getFile = useCallback((value: string) => {
        let url = "/api/freshSystem/downloadFile/" + value
        console.log(url)
        return new Promise((resolve, reject) => {
            axios({
                method: 'get',
                url,
                responseType: 'blob',
            }).then((data) => {
                console.log(data)
                resolve(data);
            }).catch((error) => {
                reject(error.toString());
            });

        });
    }, []);

    // 批量下载
    const patchDownload = (value: any) => {
        console.log(value)
        const zip = new JSZip();
        const imgsss: JSZip | null = zip.folder('批量下载');
        const promises: Promise<any>[] = [];
        value.forEach((item) => {
            const promise = getFile(item.fileId).then((data: any) => {
                // 下载文件, 文件名
                const file_name = decodeURIComponent(data.headers.get("content-disposition").split('filename=')[1].replace(/"/g, ''));
                // 逐个添加文件
                imgsss?.file(file_name, data.data, { binary: true });

            });
            promises.push(promise);
        });
        Promise.all(promises).then(() => {
            zip.generateAsync({ type: 'blob' }).then((content) => {
                // 生成二进制流,利用file-saver保存文件
                FileSaver.saveAs(content, '批量下载.zip');
            }).catch(() => {
                // 如果有资源文件下载失败，就直接用a链接下载
                message.error("压缩文件下载失败")
                // value.forEach((item) => {
                //     File.download({ url: "/api/freshSystem/downloadFile/" + item.fileId, fileName: item.name });
                // });
            });

        });
    }
    const handleExportCurrentExcel = (ExcelData: any) => { //ExcelData为后端返回的data数组
        let sheetFilter = ["key", "stuName", "stuCode", "majorLabel", "classLabel", "isRead", "phoneNumber"];
        let option = {
            fileName: '',
            datas: {
            },
        };
        option.fileName = '分群详情';
        option.datas = [
            {
                sheetData: ExcelData,
                sheetName: '分群详情',
                sheetFilter: sheetFilter,
                sheetHeader: ['序号', '姓名', '学号', '专业', '班级', '状态', '联系方式'],
                columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
            },
        ];
        var toExcel = new ExportJsonExcel(option); //new
        toExcel.saveExcel(); //保存
    }
    const handleExportCurrentExcel2 = (ExcelData: any) => { //ExcelData为后端返回的data数组
        let sheetFilter = ["key", "stuName", "stuCode", "majorLabel", "classLabel", "isRead", "phoneNumber", "receipt"];
        let option = {
            fileName: '',
            datas: {
            },
        };
        option.fileName = '分群详情';
        option.datas = [
            {
                sheetData: ExcelData,
                sheetName: '分群详情',
                sheetFilter: sheetFilter,
                sheetHeader: ['序号', '姓名', '学号', '专业', '班级', '状态', '联系方式', JSON.parse(notificationResult.form).title],
                columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
            },
        ];
        var toExcel = new ExportJsonExcel(option); //new
        toExcel.saveExcel(); //保存
    }
    const [detialTableListData, setDetialTableListData] = useState<TableListItem[]>([]);
    const [notificationResult, setNotificationResult] = useState({})
    useEffect(() => {
        console.log(props.notificationId)
        props.dispatch({
            type: 'Model_Counsellor/getNoticeDetailEffects',
            payload: {
                id: props.notificationId,
                callback: (value: any) => {
                    console.log(value)
                    setNotificationResult(value);
                    console.log(props.getDetialTableListData)
                    if (props.getDetialTableListData) {
                        let num = 0
                        columns.forEach(item => {
                            if (item.title != "序号" && item.title != "姓名" && item.title != "学号" && item.title != "专业" && item.title != "班级" && item.title != "状态" && item.title != "联系方式") {
                                columns.splice(num)
                                setTitle(false)
                                console.log(columns)
                            }
                            num++;
                        })
                        if (notificationResult.isForm == 1) {
                            console.log("添加列")
                            setTitle(true)
                            console.log(JSON.parse(notificationResult.form))
                            columns.push({
                                title: JSON.parse(notificationResult.form).title,
                                width: 120,
                                align: 'center',
                                dataIndex: 'receipt',
                            })
                        }
                        if (notificationResult.isFile == 1) {
                            console.log("添加列")
                            columns.push(
                                {
                                    title: '是否上传回执',
                                    width: 120,
                                    key: 'action',
                                    align: 'center',
                                    dataIndex: 'isUpLoad',
                                },
                                {
                                    title: '操作',
                                    width: 120,
                                    key: 'action',
                                    align: 'center',
                                    render: (_, record) => (
                                        <Space size="middle">
                                            <Button type="primary" onClick={() => getDownLoad(record.fileId)}>
                                                附件下载
                                            </Button>
                                        </Space>
                                    ),
                                },
                            )
                        }
                        setDetialTableListData(props.getDetialTableListData)
                    }
                },
            },
        });
    }, [props.getDetialTableListData, props.notificationId]);
    return (
        <PageContainer>
            <div>
                <ProCard title={<span style={titleStyle}>{`主题：${notificationResult.title}`}</span>} headerBordered>
                    <Row justify="center">
                        <Col span={20}>
                            <pre style={contentStyle} dangerouslySetInnerHTML={{ __html: notificationResult.content }} />
                        </Col>
                    </Row>
                </ProCard>

                <ProCard title={<span style={titleStyle}>{"通知详情"}</span>}>
                    <Space size={'middle'}>
                        <Button type="primary" onClick={() => downloadData(detialTableListData)}>
                            下载列表
                        </Button>
                        <Button type="primary" onClick={() => patchDownload(detialTableListData)}>
                            下载全部附件
                        </Button>
                    </Space>
                    <ProTable<TableListItem>
                        columns={columns}
                        onChange={settableData}
                        //配置表格的行选择功能。
                        rowSelection={{
                            selectedRowKeys, // 设置用户选择的行
                            onChange: (keys) => { setSelectedRowKeys(keys) }, // 更新用户选择的行
                            selections: [
                                Table.SELECTION_ALL, //全选
                                Table.SELECTION_INVERT, //反选
                                Table.SELECTION_NONE, //全不选
                            ],
                        }}
                        dataSource={detialTableListData}
                        options={{ reload: true }}
                        search={false}
                        pagination={{
                            //分页
                            pageSize: 10,
                        }}
                        rowKey="key"
                    />
                </ProCard>
            </div>
        </PageContainer>
    );
};

export default connect(({ Model_Counsellor }: any) => ({
    Model_Counsellor,

}))(DetialList);
